package com.yoomiito.app.ui.goods

import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.barlibrary.ImmersionBar
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.AppInterfaceInfo
import com.yoomiito.app.model.bean.GoodsDetail
import com.yoomiito.app.model.home.FreeGoodsBuyInfo
import com.yoomiito.app.model.sdd.ShareMsg
import com.yoomiito.app.present.goods.NewGoodsInfoPresenter
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.*
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.NewLiBaoBottomBar.*
import com.yoomiito.app.ui.anyview.goodsinfo.header.*
import com.yoomiito.app.ui.order.sureorder.singleGoods.BuyGoodsActivity
import com.yoomiito.app.ui.video.VideoPlayActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.dialog.FreeGoodsCouponDialog
import com.yoomiito.app.widget.dialog.ShareSendMoreAdDialog
import kotlinx.android.synthetic.main.act_goods_info.*

class NewGoodsInfoActivity : BaseActivity<NewGoodsInfoPresenter>() {

    private var mGoodsId: String? = null
    private var mGoodsType: Int = 0 //区分商品类型
    private var mGoodsMainType = "1"//用于请求数据
    private var shareEventId = ""
    private var freeGoodsCouponDialog: FreeGoodsCouponDialog? = null
    private lateinit var goodsDetail:GoodsDetail
    private val mGoodsAdapter = NewGoodsInfoPicAdapter(null)
    private lateinit var mBaseBottomBar: BaseBottomBar
    private lateinit var headerView:BaseGoodsInfoHeaderView
    companion object {
        /**
         * @param goodsMainType 商品大类 1 淘宝 2 自营
         */
        fun toGoodsInfo(context: Context, goodsID: String, goodsMainType: String) {
            val intent = Intent(context, NewGoodsInfoActivity::class.java)
            intent.putExtra(Const.Goods.GOODS_ID, goodsID)
            intent.putExtra(Const.Goods.GOODS_MAIN_TYPE, goodsMainType)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    public override fun initImmersionBar() {
        ImmersionBar.with(this).keyboardEnable(false).init()
    }

    override fun getLayoutId(): Int = R.layout.act_goods_info

    override fun newP(): NewGoodsInfoPresenter {
        return NewGoodsInfoPresenter(App.mAppConfig)
    }

//    override fun onSaveInstanceState(outState: Bundle) {
//        outState.putSerializable(GOODS_INFO_ACT, detail)
//        super.onSaveInstanceState(outState)
//    }
//
//    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
//        super.onRestoreInstanceState(savedInstanceState)
//        detail = savedInstanceState.getSerializable(GOODS_INFO_ACT) as GoodsDetail
//    }

    override fun initData(savedInstanceState: Bundle?) {
//        if (savedInstanceState != null) {
//            detail = savedInstanceState.getSerializable(GOODS_INFO_ACT) as GoodsDetail
//        }
        mGoodsId = intent.getStringExtra(Const.Goods.GOODS_ID)
        mGoodsMainType = intent.getStringExtra(Const.Goods.GOODS_MAIN_TYPE)
        back.setOnClickListener { finish() }
        initRcy()
        requestData()
    }

    private fun initRcy() {
        layout_rcy.layoutManager = LinearLayoutManager(this@NewGoodsInfoActivity)
        layout_rcy.adapter = mGoodsAdapter
    }

    private fun requestData() {
        showLoading()
        p.getGoodsInfo(mGoodsId, mGoodsMainType)
    }

    private fun addView(goodsDetail: GoodsDetail) {
        goodsDetail.oidCardId = mGoodsId
        addHeader(goodsDetail)
        addBottomView(goodsDetail)
    }

    //根据商品详情 获取到的商品类型 来添加顶部
    private fun addHeader(goodsDetail: GoodsDetail) {
        when(mGoodsType){
            Type.GoodsType.TaoBao-> headerView = TaoBaoGoodsInfoHeaderView(this@NewGoodsInfoActivity)
            Type.GoodsType.Gift -> headerView = LiBaoGoodsInfoHeaderView(this@NewGoodsInfoActivity)
            Type.GoodsType.BaoPin -> headerView = BaoPinGoodsInfoHeaderView(this@NewGoodsInfoActivity)
            Type.GoodsType.YouPin -> headerView = YouPinGoodsInfoHeaderView(this@NewGoodsInfoActivity)
            Type.GoodsType.FreeGift-> {
                if (App.mAppConfig.isLogin&&UserInfoConfig.getUser().three_role_id.toInt()>=Type.LevelType.SDD_VIP_10){
                    send.visibility = View.VISIBLE
                    send.setOnClickListener {
                        showLoading()
                        p.postShareNum(goodsDetail.num_iid.toString())
                       p.getSddShareMsg(6,goodsDetail.num_iid.toString())
                    }
                }
                headerView = SddVipGoodsInfoHeaderView(this@NewGoodsInfoActivity)
            }
            Type.GoodsType.GiveMore-> headerView = SddVipGoodsInfoHeaderView(this@NewGoodsInfoActivity)
        }
        headerView.OnVideoClickListener ={
            VideoPlayActivity.start(this, it)
        }
        mGoodsAdapter.setHeaderView(headerView)
        headerView.updateGoodsInfo(goodsDetail)
    }

    //根据商品详情 获取到的商品类型 来添加底部button
    private fun addBottomView(goodsDetail: GoodsDetail) {
        when(mGoodsType){
            Type.GoodsType.TaoBao-> mBaseBottomBar = NewTaoBaoBottomBar(this@NewGoodsInfoActivity)
            Type.GoodsType.Gift -> mBaseBottomBar = NewLiBaoBottomBar(this@NewGoodsInfoActivity)
            Type.GoodsType.BaoPin ->   mBaseBottomBar = NewBaoPinBottomBar(this@NewGoodsInfoActivity)
//                if(App.mAppConfig.isLogin) p.getList(1)

//                mBaseBottomBar.onClickListener = {
////                    if (Const.Goods.ADD_SHOP_CAR == it.eventType){//表示成功的点击事件
////                        showNewFlag(true)
////                    }
//                }
//                mBaseBottomBar.setOnClickClick(object : BaseBottomBar.OnClick {
//                    override fun onClick(goodsDetail: GoodsDetail, type: Int) {
//                        p.getInterface(goodsDetail.appInterface+"?productId="+ goodsDetail.id+ "&systemType=1")
//                    }
//                })
////                shopCar.visibility = View.VISIBLE
////                shopCar.setOnClickListener {
////                    if (App.mAppConfig.isLogin) {
////                        ShopCarActivity.start(this@NewGoodsInfoActivity)
////                    } else {
////                        LoginUtils.toOneKeyLogin(this)
////                    }
////                }
//            }
            Type.GoodsType.YouPin -> mBaseBottomBar = NewYouPinBottomBar(this@NewGoodsInfoActivity)
            Type.GoodsType.FreeGift-> mBaseBottomBar = FreeGoodsBottomBar(this@NewGoodsInfoActivity)
            Type.GoodsType.GiveMore-> mBaseBottomBar = SddVipGoodsBottomBar(this@NewGoodsInfoActivity)
        }
        bottomParent!!.addView(mBaseBottomBar)
        mBaseBottomBar?.updateGoodsInfo(goodsDetail)
        mBaseBottomBar.setOnClickClick(object : BaseBottomBar.OnClick {
            override fun onClick(goodsDetail: GoodsDetail, type: Int) {
                p.getInterface(goodsDetail.appInterface+"?productId="+ goodsDetail.id+ "&systemType=1")
            }
        })
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            dismissLoading()
        }
    }

    override fun eventMessage(eventMessage: EventMessage) {
        super.eventMessage(eventMessage)
        if (mGoodsType == AllCode.BaoPin && AllCode.NotifyShopCarData == eventMessage.eventType) {//刷新购物车数据
//            p!!.getList(1)
        }
        if (AllCode.LoginSuccess == eventMessage.eventType) {//登录成功 返回商品详情的上一级
            if (mGoodsType==Type.GoodsType.TaoBao){
                this.finish()
            }else{
                requestData()
//                headerView?.updateGoodsInfo(goodsDetail)
//                mBaseBottomBar?.updateGoodsInfo(goodsDetail)
            }
        }
        if (Type.EventMsgType.BuyComplete == eventMessage.eventType) {//购买成功刷新数据
            requestData()
        }
        if (Type.EventMsgType.NotifyShopCarData == eventMessage.eventType) {//购买成功刷新数据
            requestData()
        }

//        if (Type.EventMsgType.UPDATE_USER_INFO == eventMessage.eventType){
//            mBaseBottomBar.updateGoodsInfo(goodsDetail)
//        }
    }


    //友盟埋点事件id
    private fun setUMengPoint(type: Int) {
        when (type) {
            AllCode.TaoBao -> shareEventId = "taobaoProductDetailPageShareClick"
            AllCode.BaoPin -> shareEventId = "hotProductDetailPageShareClick"
            AllCode.Gift -> shareEventId = "giftProductDetailPageShareClick"
        }
    }

    /**
     * @param detail
     */
    fun setGoodsInfo(detail: GoodsDetail?) {
        dismissLoading()
        if (detail == null) {
            pullMarket("未知错误，请重试")
            return
        }
        goodsDetail = detail
         mGoodsType = DataUtils.getGoodsType(2, detail.product_type)
        if (mGoodsType != -1) {
            setUMengPoint(mGoodsType)
        }
        addView(detail)
        mGoodsAdapter.setNewData(goodsDetail.details.split(","))
    }

    fun sddShareMsg(msg:ShareMsg){
        val dialog = ShareSendMoreAdDialog(this,goodsDetail,msg,ShareSendMoreAdDialog.GoodsDetailType)
        dialog.setOnShowListener {
            dismissLoading()
        }
        dialog.show()
    }

    fun showNewFlag(show: Boolean) {
        if (AllCode.BaoPin==mGoodsType) {
            show_new_flag.visibility = if (show) View.VISIBLE else View.GONE
            val d = show_new_flag.background as GradientDrawable
            d.setColor(ResUtil.getColor(R.color.color_FF035B))
        }
    }

    fun buyFreeGoods(url: String) {
        RouterUtils.TaoBaoWithUrl(url)
    }

    fun showFreeGoodsCouponDialog(freeGoodsBuyInfo: FreeGoodsBuyInfo) {
        if (freeGoodsCouponDialog == null) {
            freeGoodsCouponDialog = FreeGoodsCouponDialog(this)
            freeGoodsCouponDialog!!.setFreeGoodsBuyInfo(freeGoodsBuyInfo)
            freeGoodsCouponDialog!!.setOnViewClickListener { view -> buyFreeGoods(freeGoodsBuyInfo.send_url) }
        }
        freeGoodsCouponDialog!!.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

    //商品下架处理
    fun pullMarket(msg: String) {
        if (!TextUtils.isEmpty(msg)) {
            msg.showToast()
        }
        finish()
    }

    fun jumpBuy(appInterfaceInfo: AppInterfaceInfo) {
        BuyGoodsActivity.start(context, goodsDetail,appInterfaceInfo, Type.GoodsType.Gift)
    }

}
